package com.juzhencms.apps.busi.web;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.MD5Util;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;

@Controller
@RequestMapping("/sensitiveKeywords")
public class SensitiveKeywordsController extends BaseController {

	// 查询所有敏感词
	@RequestMapping(value = "/gridlistData", produces = "text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request) {
		Map data = new HashMap();
		List whereParamList = new ArrayList();
		String where = "where del_flag=0";

		if (request.getParameter("publish") != null && !request.getParameter("publish").toString().trim().equals("")) {
			where += " and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}

		if (request.getParameter("category_id") != null
				&& !request.getParameter("category_id").toString().trim().equals("")) {
			where += " and category_id = ? ";
			whereParamList.add(request.getParameter("category_id"));
		}

		if (request.getParameter("name") != null && !request.getParameter("name").toString().trim().equals("")) {
			String name = request.getParameter("name");
			where += " and name like ? ";
			whereParamList.add("%" + request.getParameter("name") + "%");
		}

		// 分页处理
		int pageIndex = 1;
		if (request.getParameter("pageIndex") != null
				&& !request.getParameter("pageIndex").toString().trim().equals("")) {
			pageIndex = new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize = 10;
		if (request.getParameter("pageSize") != null
				&& !request.getParameter("pageSize").toString().trim().equals("")) {
			pageSize = new Integer(request.getParameter("pageSize")).intValue();
		}
		int start = 0;
		if (pageIndex > 1) {
			start = (pageIndex - 1) * pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);

		// 排序参数
		String sortField = "id";
		String sortOrder = "desc";
		if (request.getParameter("sortField") != null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if (request.getParameter("sortOrder") != null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");

		// 查询列表数据
		List dataList = this.getCommonService().getJdbcDao().querySql("select * from " + DBTable.sensitiveKeywords + " "
				+ where + " order by " + sortField + " " + sortOrder + " limit ?,?", whereParamList.toArray());
		if (dataList != null && dataList.size() > 0) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (int i = 0; i < dataList.size(); i++) {
				Map row = (Map) dataList.get(i);
				Date date = (Date) row.get("create_time");
				row.put("create_time", sdf.format(date));
				// 查询创建人
				int create_userid = new Integer(row.get("create_user").toString());
				Map getUser = this.getCommonService().getJdbcDao().queryRow(
						"select name from " + DBTable.user + " where id=?  limit 1", new Object[] { create_userid });
				if (getUser != null) {
					row.put("create_user", getUser.get("name").toString());
				} else {
					row.put("create_user", "");
				}
				// 所属分类
				int category_id = new Integer(row.get("category_id").toString());
				Map get_category_info = this.getCommonService().getJdbcDao().queryRow(
						"select name from " + DBTable.sensitiveCategory + " where id=?  limit 1",
						new Object[] { category_id });
				if (get_category_info != null) {
					row.put("category_name", get_category_info.get("name").toString());
				} else {
					row.put("category_name", "");
				}
			}
		}
		// 查询总条数
		Map countRow = this.getCommonService().getJdbcDao().queryRow(
				"select count(id) as count_num from " + DBTable.sensitiveKeywords + " " + where,
				whereParamList.subList(0, whereParamList.size() - 2).toArray());
		int recordsTotal = 0;
		if (countRow.get("count_num") != null) {
			recordsTotal = new Integer(countRow.get("count_num").toString()).intValue();
		}

		// 拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);

		return WebUtil.resultString(data, request);
	}

	// 保存敏感词
	@RequestMapping(value = "/save", produces = "text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request) {

		Map data = JSON.parseObject(request.getParameter("data"), Map.class);
		data.put("del_flag", 0);
		String id = null;
		if (data.get("id") != null) {
			id = data.get("id").toString();
		}

		if (id == null || id.equals("")) {

			if (data.get("create_time") == null || data.get("create_time").equals("")) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = new Date();
				data.put("create_time", sdf.format(date));
			}
			String name = (String) data.get("name");
			Map tmpcate = this.getCommonService().getJdbcDao().queryRow("select * from " + DBTable.sensitiveKeywords
					+ " where name=?  and del_flag = 0 and publish=1 limit 0,1", new Object[] { name });
			if (tmpcate != null) {
				Map result = new HashMap();
				result.put("result", 0);
				result.put("msg", "敏感词已存在，请重新输入");
				return WebUtil.resultString(result, request);
			}
			this.getCommonService().getJdbcDao().addObj(DBTable.sensitiveKeywords, data);
		} else {
			// if(data.get("update_time")==null ||
			// data.get("update_time").equals("")){
			// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
			// HH:mm:ss");
			// Date date = new Date();
			// data.put("update_time", sdf.format(date));
			// }
			String name = (String) data.get("name");
			Map tmpcate = this.getCommonService().getJdbcDao().queryRow(
					"select * from " + DBTable.sensitiveKeywords
							+ " where name=? and id !=?  and del_flag = 0 and publish=1 limit 0,1",
					new Object[] { name, id });
			if (tmpcate != null) {
				Map result = new HashMap();
				result.put("result", 0);
				result.put("msg", "敏感词已存在，请重新输入");
				return WebUtil.resultString(result, request);
			}
			this.getCommonService().getJdbcDao().updateObj(DBTable.sensitiveKeywords, data, "id");
		}

		Map result = new HashMap();
		result.put("result", 1);
		result.put("msg", "保存成功");

		return WebUtil.resultString(result, request);

	}

	// 敏感词编辑
	@RequestMapping(value = "/detailData/{id}", produces = "text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id, HttpServletRequest request) {
		Map data = new HashMap();
		Map record = this.getCommonService().getJdbcDao().queryRow(
				"select * from " + DBTable.sensitiveKeywords + " where del_flag=0 and id=?", new Object[] { id });
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date) record.get("create_time");
		record.put("create_time", sdf.format(date));
		data.put("data", record);

		return WebUtil.resultString(data, request);
	}

	// 删除敏感词
	@RequestMapping(value = "/delete", produces = "text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request) {

		Map data = JSON.parseObject(request.getParameter("data"), Map.class);

		String id = null;
		if (data.get("id") != null) {
			id = data.get("id").toString();
		}

		if (id == null || id.equals("")) {
		} else {
			String[] idArray = id.split(",");
			String tmpVar = "?";
			if (idArray != null && idArray.length > 0) {
				Matcher matcher = Pattern.compile("\\d+").matcher(id);
				tmpVar = matcher.replaceAll("?");
			}
			// this.getCommonService().getJdbcDao().updateSql("delete from
			// "+DBTable.member+" where id in ("+tmpVar+")",idArray);
			this.getCommonService().getJdbcDao().updateSql(
					"update " + DBTable.sensitiveKeywords + " set del_flag=1 where id in (" + tmpVar + ")", idArray);
		}
		Map result = new HashMap();
		result.put("result", 1);
		result.put("msg", "操作成功");

		return WebUtil.resultString(result, request);
	}

	// 更新发布状态
	@RequestMapping(value = "/updatePublish", produces = "text/html; charset=UTF-8")
	@ResponseBody
	public String updatePublish(HttpServletRequest request) {
		String num = "1".equals(request.getParameter("publish")) ? "0" : "1";

		this.getCommonService().getJdbcDao().updateSql(
				"update " + DBTable.sensitiveKeywords + " set publish=? where id=?",
				new Object[] { num, request.getParameter("id") });
		Map result = new HashMap();
		result.put("result", 1);
		result.put("msg", "操作成功");

		return WebUtil.resultString(result, request);
	}

}
